//go:build windows

package IntelIpps

/*
#cgo CFLAGS: -ID:/DevelopTools/IPPS2022/ipp/2021.12/include
#cgo LDFLAGS: -LD:/DevelopTools/IPPS2022/ipp/2021.12/lib -lipps -lippcore
#include <ipp.h>
#include <stdlib.h>
*/
import "C"
import (
	"errors"
	"go.uber.org/zap"
	"lht-go-plugins/LhtLog"
	"lht-go-plugins/internal/core"
)

import (
	"encoding/json"
)

type IppsPlugin struct {
	*core.BasePlugin
	ipp IComputingInterface
}

func NewIppsPlugin() *IppsPlugin {
	return &IppsPlugin{
		BasePlugin: core.NewBasePlugin("ipps", 1001),
		ipp:        IPP,
	}
}

// Init 初始化 IPP 库（必须在 Start 前调用）
func (p *IppsPlugin) Init(_ any) error {
	// 调用 ippInit() 初始化 IPP 核心
	status := C.ippInit()
	if status != C.ippStsNoErr {
		return errors.New("IPP initialization failed: " + C.GoString(C.ippGetStatusString(status)))
	}

	// 可选：打印 IPP 版本信息
	lib := C.ippsGetLibVersion()
	if lib != nil {
		// 注意：C 字符串需要转换
		name := C.GoString(lib.Name)
		version := C.GoString(lib.Version)
		LhtLog.Info("IPP Library Loaded", zap.String("name", name), zap.String("version", version))
	}

	LhtLog.Info("IppsPlugin initialized successfully")
	return nil
}
func (p *IppsPlugin) Start() error {
	return p.BasePlugin.Start(p.handleData)
}

type handlerFunc func(args json.RawMessage) (interface{}, string)

var handlers = map[string]handlerFunc{
	"sort_float": handleSortFloat,
	"fft_float":  handleFFTFloat,
	// ...
}

func (p *IppsPlugin) handleData(data []byte) {
	var msg struct {
		RequestID string          `json:"request_id"`
		Method    string          `json:"method"`
		Args      json.RawMessage `json:"args"`
	}
	if err := json.Unmarshal(data, &msg); err != nil {
		p.respond("", nil, err.Error())
		return
	}

	h := handlers[msg.Method]
	if h == nil {
		p.respond(msg.RequestID, nil, "unknown method")
		return
	}

	result, errMsg := h(msg.Args)
	p.respond(msg.RequestID, result, errMsg)
}

func (p *IppsPlugin) respond(id string, data interface{}, err string) {
}

func handleSortFloat(raw json.RawMessage) (interface{}, string) {
	var args struct {
		In     []float32 `json:"in"`
		Ascend bool      `json:"ascend"`
	}
	if err := json.Unmarshal(raw, &args); err != nil {
		return nil, err.Error()
	}
	return IPP.SortFloat(args.In, args.Ascend), ""
}
func handleFFTFloat(raw json.RawMessage) (interface{}, string) {
	var args struct {
		real []float32 `json:"real"`
		imag []float32 `json:"imag"`
	}
	if err := json.Unmarshal(raw, &args); err != nil {
		return nil, err.Error()
	}
	return IPP.FFTFloat(args.real, args.imag), ""
}
